$(function () {
  render();
  async function render() {
    let res = await $.ajax({
      url: "http://www.liulongbin.top:3006/api/getbooks",
    });
    console.log(res.data);
    let data = res.data
      .map((item) => {
        return `<tr>
            <th scope="row">${item.id}</th>
            <td>${item.bookname}</td>
            <td>${item.author}</td>
            <td>${item.publisher}</td>
            <td><button data-id = "${item.id}">del</button></td>></tr>
            `;
      })
      .join("");
    $(".table tbody").html(data);
  }
  $("table").on("click", "button", async function () {
    let index = $(this).attr("data-id");
    console.log(index);
    $(this).parent().parent().remove();
    let res = await $.ajax({
      url: "http://www.liulongbin.top:3006/api/delbook",
      data: {
        id: index,
      },
    });
    console.log(res);
  });
  $(".myBtn").click(async function () {
    let res = await $.ajax({
      method: "POST",
      url: "http://www.liulongbin.top:3006/api/addbook",
      data: {
        bookname: $("#ipt_bookname").val(),
        author: $("#ipt_author").val(),
        publisher: $("#ipt_publisher").val(),
      },
    });
    console.log(res);
    render();
  });
});
